package com.xiumu.controller.sys;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiumu.common.core.constants.XiuMuConst;
import com.xiumu.common.core.enums.RequestOperateType;
import com.xiumu.common.core.result.ResultJSON;
import com.xiumu.common.redis.RedisService;
import com.xiumu.pojo.sys.dto.LoginDTO;
import com.xiumu.pojo.sys.entity.User;
import com.xiumu.pojo.sys.vo.CaptchaVO;
import com.xiumu.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 登录退出
 *
 * @author XiuMu
 * @date 2022-07-16 17:27:37
 */
@RestController
public class TokenController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录接口，返回 token
     *
     * @param loginDTO 登录凭证
     * @return
     */
    @GetMapping("/token")
    public ResultJSON<String> token(@Validated LoginDTO loginDTO) {
        User user = userService.login(loginDTO);
        StpUtil.login(user.getId());
        StpUtil.getSession().set(XiuMuConst.USERNAME, user.getUsername());
        return ResultJSON.success(StpUtil.getTokenInfo().tokenValue, RequestOperateType.LOGIN).setMsg("登录成功");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public ResultJSON<Boolean> logout() {
        System.out.println("退出" + StpUtil.getSession());
        StpUtil.logout();
        return ResultJSON.success(true, RequestOperateType.LOGOUT).setMsg("退出成功");
    }

    /**
     * 生成验证码
     *
     * @return
     */
    @GetMapping("/captcha")
    public ResultJSON<CaptchaVO> captcha() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(150, 40, 4, 50);
        String captchaId = IdWorker.getIdStr();
        redisService.setCacheObject(XiuMuConst.CAPTCHA_PREFIX + captchaId, captcha.getCode(), 5 * 60);
        return ResultJSON.querySuccess(new CaptchaVO(captchaId, captcha.getImageBase64())).setMsg("刷新成功");
    }

}
